package ca.paulshin.yunatube.youtube;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleExpandableListAdapter;
import ca.paulshin.yunatube.R;
import ca.paulshin.yunatube.YunaTubeBaseFragment;
import ca.paulshin.yunatube.common.Utils;
import ca.paulshin.yunatube.database.Schema.YouTubeColumns;
import ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase;

import com.squareup.picasso.Picasso;

public class SectionFragment extends YunaTubeBaseFragment {
	public static final String EXTRA_SECTION_ID = "extra_section_id";
	public static final String EXTRA_TITLE = "extra_title";

	private static List<List<String>> groupTitles, groupUrls;
	private List<HashMap<String, String>> groupList;

	private YuNaTubeSqliteDatabase database;

	private ExpandableListView sectionList;
	private LinearLayout sectionLayout;

	private int sectionId;

	public static SectionFragment getInstance(int secitonId, int title) {
		SectionFragment fragment = new SectionFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(EXTRA_SECTION_ID, secitonId);
		bundle.putInt(EXTRA_TITLE, title);
		fragment.setArguments(bundle);
		return fragment;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.youtube_section, null);
		sectionId = getArguments().getInt(EXTRA_SECTION_ID);

		database = YuNaTubeSqliteDatabase.getInstance();

		// ExpandableListView
		sectionList = (ExpandableListView) view.findViewById(R.id.section_list);
		sectionList.setDividerHeight(0);
		groupTitles = new ArrayList<List<String>>();
		groupUrls = new ArrayList<List<String>>();
		groupList = createGroupList();

		SimpleExpandableListAdapter expListAdapter = new MySimpleExpandableListAdapter(getActivity(), groupList, // groupData describes the first-level entries
				R.layout.group_row, // Layout for the first-level entries
				new String[] { "category" }, // Key in the groupData maps to display
				new int[] { R.id.childname }, // Data under "colorName" key goes into this TextView
				createChildList(), // childData describes second-level entries
				R.layout.child_row, // Layout for second-level entries
				new String[] { "clip" }, // Keys in childData maps to display
				new int[] { R.id.childname } // Data under the keys above go into these TextViews
		);
		sectionList.setAdapter(expListAdapter);

		// set background
		sectionLayout = (LinearLayout) view.findViewById(R.id.section_layout);
		boolean isKorean = Utils.isAppLocaleKorean();

		switch (sectionId) {
		case R.string.submenu_youtube_greetings_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_greetings_bg_bitmap_ko : R.drawable.youtube_greetings_bg_bitmap_en);
			if (sectionList.getCount() > 0)
				sectionList.expandGroup(0);
			break;

		case R.string.submenu_youtube_competitions_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_competitions_bg_bitmap_ko : R.drawable.youtube_competitions_bg_bitmap_en);
			break;

		case R.string.submenu_youtube_iceshows_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_iceshows_bg_bitmap_ko : R.drawable.youtube_iceshows_bg_bitmap_en);
			break;

		case R.string.submenu_youtube_offtheice_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_offtheice_bg_bitmap_ko : R.drawable.youtube_offtheice_bg_bitmap_en);
			break;

		case R.string.submenu_youtube_knc_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_kissncry_bg_bitmap_ko : R.drawable.youtube_kissncry_bg_bitmap_en);
			break;

		case R.string.submenu_youtube_jukebox_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_jukebox_bg_bitmap_ko : R.drawable.youtube_jukebox_bg_bitmap_en);
			if (sectionList.getCount() > 0)
				sectionList.expandGroup(0);
			break;

		case R.string.submenu_youtube_muhan_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_muhan_bg_bitmap_ko : R.drawable.youtube_muhan_bg_bitmap_en);
			break;

		case R.string.submenu_youtube_guru_id:
			sectionLayout.setBackgroundResource(isKorean ? R.drawable.youtube_guru_bg_bitmap_ko : R.drawable.youtube_guru_bg_bitmap_en);
			if (sectionList.getCount() > 0)
				sectionList.expandGroup(0);
			break;
		}

		sectionList.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				String category = groupList.get(groupPosition).get("category");
				String title = groupTitles.get(groupPosition).get(childPosition);
				String url = groupUrls.get(groupPosition).get(childPosition);

				Bundle bundle = new Bundle();
				bundle.putStringArray(YouTubeActivity.EXTRA_YOUTUBE_CLIPSET, new String[] { category, title, url });
				Intent intent = new Intent(SectionFragment.this.getActivity(), YouTubeActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);

				return false;
			}
		});

		return view;
	}

	private List<HashMap<String, String>> createGroupList() {
		List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
		Cursor cursor = database.fetchCategories(getString(sectionId));

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			HashMap<String, String> m = new HashMap<String, String>();
			m.put("category", cursor.getString(cursor.getColumnIndexOrThrow(YouTubeColumns.category)));
			result.add(m);
		}
		if (cursor != null)
			cursor.close();
		return result;
	}

	private List<List<HashMap<String, String>>> createChildList() {
		List<List<HashMap<String, String>>> result = new ArrayList<List<HashMap<String, String>>>();
		List<HashMap<String, String>> setList;

		List<String> childTitles;
		List<String> childUrls;
		Cursor cursor = null;

		HashMap<String, String> child;
		String groupTitle;
		for (int i = 0; i < groupList.size(); i++) {
			setList = new ArrayList<HashMap<String, String>>();
			groupTitle = groupList.get(i).get("category");

			cursor = database.query(getString(sectionId), new String[] { YouTubeColumns.title, YouTubeColumns.url }, YouTubeColumns.category + "=\"" + groupTitle + "\"", null, null, null,
					YouTubeColumns._ID);

			childTitles = new ArrayList<String>();
			childUrls = new ArrayList<String>();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				child = new HashMap<String, String>();
				child.put("clip", cursor.getString(cursor.getColumnIndexOrThrow(YouTubeColumns.title)));
				childTitles.add(cursor.getString(cursor.getColumnIndexOrThrow(YouTubeColumns.title)));
				childUrls.add(cursor.getString(cursor.getColumnIndexOrThrow(YouTubeColumns.url)));
				setList.add(child);
			}

			// one category is done.
			result.add(setList);
			groupTitles.add(childTitles);
			groupUrls.add(childUrls);
		}
		if (cursor != null)
			cursor.close();
		return result;
	}

/*
	private void clearApplicationCache(java.io.File dir) {
		if (dir == null)
			dir = getActivity().getCacheDir();
		else
			;
		if (dir == null)
			return;
		else
			;
		java.io.File[] children = dir.listFiles();
		try {
			for (int i = 0; i < children.length; i++)
				if (children[i].isDirectory())
					clearApplicationCache(children[i]);
				else
					children[i].delete();
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		clearApplicationCache(null);
	}
*/

	private class MySimpleExpandableListAdapter extends SimpleExpandableListAdapter {
		public MySimpleExpandableListAdapter(Context context, List<? extends Map<String, ?>> groupData, int groupLayout, String[] groupFrom, int[] groupTo,
				List<? extends List<? extends Map<String, ?>>> childData, int childLayout, String[] childFrom, int[] childTo) {
			super(context, groupData, groupLayout, groupFrom, groupTo, childData, childLayout, childFrom, childTo);
		}

		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			final View itemRenderer = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
			final ImageView thumbnail = (ImageView) itemRenderer.findViewById(R.id.thumbnail);
			Picasso.with(getActivity()).load("http://i.ytimg.com/vi/" + groupUrls.get(groupPosition).get(childPosition) + "/2.jpg").placeholder(R.drawable.stub).resize(120, 90).into(thumbnail);

			return itemRenderer;
		}
	}

	@Override
	public int getTitle() {
		return getArguments().getInt(EXTRA_TITLE);
	}

	@Override
	protected boolean getNetworkCheck() {
		return false;
	}

	@Override
	protected String getTrackerId() {
		return "youtube - section";
	}
}
